const request = require('../util/request')
const { URL } = require('url')
const { join } = require('path')
var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxy(); // See (†)

exports.getGlobalConfig = async function() {
    const data = await request.get('/config', {})
    return data
}

exports.login = async function(username, password) {
    const data = await request.request({
        method: 'POST',
        url: '/user/login',
        data: JSON.stringify({
            username,
            password,
        }),
        headers: {
            'Content-Type': 'application/json'
        }
    })
    return data
}

exports.info = async function(token) {
    const data = await request.request({
        method: 'GET',
        url: '/user/info',
        params: {
            token,
        }
    })
    return data
}

exports.getUserByUserName = async function(username) {
    const data = await request.get('/user', {
        params: {
            username,
        }
    })
    return data
}

exports.getUserRepos = async function(username) {
    const data = await request.get('/user/repos', {
        params: {
            username
        }
    })
    return data
}

exports.updateUserOverviews = async function(username, overviews) {
    const res = await request.request({
        url: '/user/repo/overviews',
        method: 'PUT',
        data: JSON.stringify({
            username,
            overviews
        }),
        headers: {
            'Content-Type': 'application/json'
        }
    })
    return res
}

exports.updateUserProfile = function(req, res, query) {
    return new Promise(resolve => {
        req.url = ''
        const target = new URL(request.defaults.baseURL)
        target.pathname = join(target.pathname, '/user/profile')
        Object.keys(query).forEach(key => {
            target.searchParams.set(key, query[key])
        })
        proxy.web(req, res, { target: target.href }, function(e) {
            resolve(e)
        });
    })
}

exports.updateBranchProfile = async function updateBranchProfile(params) {
    const {username, repo, description, website} = params
    const data = await request.put('/user/repo/profile', JSON.stringify({
        username,
        repo,
        description,
        website,
    }), {
        headers: {
            'Content-Type': 'application/json',
        }
    })
    return data
}

exports.getAvatar = async function(username) {
    const response = await request.request({
        url: '/user/info/avatar',
        method: 'GET',
        params: {
            username,
        },
        responseType: 'stream'
    })
    return response
}